package org.snail.message.service.option;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.open.client.api.model.corp.MessageBody;
import com.dingtalk.open.client.api.model.corp.MessageType;
import com.dingtalk.open.client.common.ServiceException;
import lombok.extern.log4j.Log4j;
import org.snail.common.dingding.auth.AuthHelper;
import org.snail.common.dingding.chat.ChatHelper;
import org.snail.common.dingding.media.MediaHelper;
import org.snail.common.dingding.utils.JedisUtils;
import org.snail.constant.CacheNameConstant;
import org.snail.constant.CommonConstant;
import org.snail.constant.ErrCodeConstant;
import org.snail.constant.GroupConstant;
import org.snail.exception.BaseException;
import org.snail.exception.CommonException;
import org.snail.exception.EmpException;
import org.snail.other.bean.DingDingDO;
import org.snail.other.bean.GroupDO;
import org.snail.other.bean.GroupNotificationDTO;
import org.snail.other.mapper.GroupMapper;
import org.snail.other.service.impl.SendMessageServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Log4j
public class GroupMessageOption {

    @Autowired
    private JedisUtils jedisUtils;
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private SendMessageServiceImpl sendMessageService;

    public void sendGroupMessage(GroupNotificationDTO groupNotificationDTO){
        List<Long> ids = groupNotificationDTO.getIds();
        log.error("前端传递过来的群的id:"+ids);
        Integer sendType = groupNotificationDTO.getSendType();
        //文本发送
        if (GroupConstant.TEXT_MSG == sendType) {
            sendText(groupNotificationDTO,GroupConstant.ERR_NUMBER);
        }else if(GroupConstant.LINK_MSG == sendType){
            sendLink(groupNotificationDTO);
            //链接发送end
        }else{     //TODO  这个不要直接用else,万一还有其他类型怎么办   ， 用else if     最后用else 进行异常判断
            sendFile(groupNotificationDTO);
        }

    }

    private void sendText(GroupNotificationDTO groupNotificationDTO,Integer errNum){
        List<Long> ids = groupNotificationDTO.getIds();
        MessageBody.TextBody textBody = new MessageBody.TextBody();
        textBody.setContent(groupNotificationDTO.getText());
        if (null == groupNotificationDTO || null == groupNotificationDTO.getIds() || null == groupNotificationDTO.getSendType() || StringUtils.isEmpty(groupNotificationDTO.getText())) {
            log.error("钉钉群消息发送缺失重要参数！参数详情：" + groupNotificationDTO);
            try {
                throw new CommonException(ErrCodeConstant.ILLEGAL_PARAM, "钉钉群消息发送缺失重要参数！");
            } catch (CommonException e) {
                log.error("钉钉群消息发送确实重要参数!");
            }
        }
        log.error("======================通过chatId开始群发消息咯:~~~~~~~~~~");
        for(int i=0;i<ids.size();i++){
            Long groupId = ids.get(i);
            GroupDO groupById = groupMapper.findGroupById((long) groupId);
            if (null == groupById) {
                log.error("根据群组id，不能查找到相关群组！群组详细信息：" + groupById);
                continue;
            }
            if (!StringUtils.isEmpty(groupById.getHookUrl())) {
                List<String> hookUrls = new ArrayList<>();
                hookUrls.add(groupById.getHookUrl());
                groupNotificationDTO.setWebhookURL(hookUrls);
                try {
                    sendMessageService.groupNotification(groupNotificationDTO);
                } catch (EmpException e) {
                    log.error(e.getMessage());
                    continue;
                }
            } else if (!StringUtils.isEmpty(groupById.getChatId())) {
                if (StringUtils.isEmpty(groupById.getChatId())) {
                    log.error("发送钉钉内部群操作中，缺失重要参数chatId! groupNotificationDTO ：" + groupNotificationDTO);
                    continue;
                }
                //TODO 暂时只群发文本内容，后期会进行修改
                try {
                    Thread.sleep(5000);
                    ChatHelper.sendMessageToChat(AuthHelper.getAccessToken(), groupById.getChatId(), CommonConstant.BJC_DINGID, MessageType.TEXT, textBody);
                    log.error("群的名字:"+groupById.getGroupName()+"消息为:"+groupNotificationDTO.getText());
                } catch (InterruptedException e) {
                    log.error(e.getMessage());
                } catch (ServiceException e) {
                    //控制系统繁忙次数
                    if(errNum>0) {
                        ids.add(groupId);
                    }else{
                        log.error(e.getMessage());
                    }
                    errNum--;
                    continue;
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        }
        log.error("======================通过chatId群发消息结束咯:~~~~~~~~~~");
        //文本发送结束
    }
    private void sendLink(GroupNotificationDTO groupNotificationDTO){
        List<Long> ids = groupNotificationDTO.getIds();
        //链接发送
        for(int i=0;i<ids.size();i++){
            Long id = ids.get(i);
            GroupDO groupDO = null;
            try {
                groupDO = (GroupDO) jedisUtils.getHashCache(CacheNameConstant.GROUP_ID_HASH,id+"");
            } catch (BaseException e) {
                log.error(e.getMessage());
            }
            String chatId = groupDO.getChatId();
            String hookUrl = groupDO.getHookUrl();
            if(!StringUtils.isEmpty(chatId)){
                try {
                    Thread.sleep(5000);
                    DingDingDO dingDingDO = new DingDingDO();
                    dingDingDO.setChatid(chatId);
                    Map map = new HashMap<>();
                    map.put("messageUrl",groupNotificationDTO.getLinkPath());
                    map.put("text",groupNotificationDTO.getText());
                    map.put("title",groupNotificationDTO.getTheme());
                    map.put("picUrl","https://gw.alicdn.com/tps/TB1FN16LFXXXXXJXpXXXXXXXXXX-256-130.png");
                    dingDingDO.setLink(map);
                    MediaHelper.DDLinkSend(JSONObject.toJSONString(dingDingDO));
                } catch (Exception e) {
                    log.error(e.getMessage());
                }

            }else if(!StringUtils.isEmpty(hookUrl)){
                List<String> hookUrls = new ArrayList<>();
                hookUrls.add(hookUrl);
                groupNotificationDTO.setWebhookURL(hookUrls);
                try {
                    sendMessageService.groupNotification(groupNotificationDTO);
                } catch (EmpException e) {
                    log.error(e.getMessage());
                }
                log.error("············我看一下我这500条数据 在群里发了多少条:"+i);
            }else{
                log.error("链接发送时此id的chatId和hookURL都为空:"+ids.get(i));
            }

        }
    }
    private void sendFile(GroupNotificationDTO groupNotificationDTO){
        log.error("发送文件开始!!!");
        log.error("参数:"+groupNotificationDTO);
        List<Long> ids = groupNotificationDTO.getIds();
        //文件发送
        List<String> mediaIdList = groupNotificationDTO.getMediaIdList();
        List<String> mediaTypeList = groupNotificationDTO.getMediaTypeList();
        for (Long groupId : ids) {
            GroupDO groupDO = null;
            try {
                groupDO = (GroupDO) jedisUtils.getHashCache(CacheNameConstant.GROUP_ID_HASH, groupId + "");
                log.error("从缓存中获取的groupDO:"+groupDO);
            } catch (BaseException e) {
                log.error(e.getMessage());
            }
            String chatId = groupDO.getChatId();
            for(int i=0,j=mediaIdList.size();i<j;i++){
                String mediaType = mediaTypeList.get(i);
                String mediaId = mediaIdList.get(i);
                if(StringUtils.isEmpty(mediaType)||StringUtils.isEmpty(mediaId)){
                    log.error("上传文件时groupId为"+groupId+"的mediaType或者mediaId为空,mediaId:"+mediaId+"mediaType:"+mediaType);
                }
                if(!StringUtils.isEmpty(chatId)) {
                    try {
                        Thread.sleep(5000);
                        DingDingDO dingDingDO = new DingDingDO();
                        dingDingDO.setChatid(chatId);
                        dingDingDO.setMsgtype(mediaType);
                        Map map = new HashMap<>();
                        map.put("media_id",mediaId);
                        if(MediaHelper.TYPE_IMAGE.equals(mediaType)){
                            dingDingDO.setImage(map);
                        }else{
                            dingDingDO.setFile(map);
                        }
                        log.error("群文件发送参数:"+dingDingDO);
                        MediaHelper.DDUpFile(JSONObject.toJSONString(dingDingDO));
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }

                }
            }
        }
    }
}